package com.lichuandi.springbootdemo1.service;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;

/**
 * @author Lichuandi
 * @version 1.0
 * @program : springbootdemo1
 * @ClassName QRCodeServiceImpl
 * @description :
 * @create: 2025-01-09 15:35
 **/
@Service
@Slf4j
public class QRCodeServiceImpl implements QRCodeService {
//    @Override
//    public String generateQRCode() {
//        return null;
//    }

    @Override
    public void generateQRCodeImage(String text, int width, String filePath) {
        // 实现生成二维码图片的逻辑
        // ...
        System.out.println("生成二维码图片的逻辑");
        //通过支付链接生成二维码
        HashMap<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        hints.put(EncodeHintType.MARGIN, 2);
        try {
            //把code_url包装到二维码图片
            BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, 200, 200, hints);
          //  MatrixToImageWriter.writeToStream(bitMatrix, "PNG", response.getOutputStream());
          Path path = FileSystems.getDefault().getPath(filePath);
          MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
   @Override
    public void makeQRCode(String url, HttpServletResponse response) {
        //通过支付链接生成二维码
        HashMap<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        hints.put(EncodeHintType.MARGIN, 2);
        try {
            //把code_url包装到二维码图片BitMatrix
            BitMatrix bitMatrix = new MultiFormatWriter().encode("23343", BarcodeFormat.QR_CODE, 200, 200, hints);
            MatrixToImageWriter.writeToStream(bitMatrix, "PNG", response.getOutputStream());
            response.setContentType("image/png");
            if (log.isInfoEnabled()) {
                log.info("二维码生成成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
